package cn.echisan.springbootjwtdemo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@Order(101)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //处理所有请求，注意@Order(101)，这是后面的一个
        http.requestMatcher(new AntPathRequestMatcher("/**"))
                .authorizeRequests(authorizeRequests ->
                        authorizeRequests
                                .antMatchers("/web/**").hasRole("VIP1")
                                .antMatchers("/level1/**").hasRole("VIP1")
                                .antMatchers("/level2/**").hasRole("VIP2")
                                .antMatchers("/level3/**").hasRole("VIP3")
                                .anyRequest().authenticated())
                .formLogin(formLogin ->
                        formLogin.loginPage("/web/login")
                                .loginProcessingUrl("/web/loginProcessingUrl")
                                .defaultSuccessUrl("/web/hello")
                                .permitAll()
                )
                .logout(logout ->
                        logout.invalidateHttpSession(false)
                                .logoutUrl("/web/logout")
                                .logoutSuccessUrl("/web/login")
                )
                .csrf(withDefaults())
                .rememberMe(withDefaults());
    }

    /**
     * 授权
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
                .withUser("zhangsan").password("123456").roles("VIP1", "VIP2")
                .and()
                .withUser("lisi").password("123456").roles("VIP2", "VIP3")
                .and()
                .withUser("wangwu").password("123456").roles("VIP1", "VIP3");

    }
}
